package com.gzwanchuang.xhgj.ui.page.mine;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.bridge.data.bean.HeXiaoBean;
import com.gzwanchuang.xhgj.bridge.data.repository.Apis;
import com.gzwanchuang.xhgj.bridge.request.MineRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.mine.HeXiaoZhangChaViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentHeXiaoZhangChaBinding;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.xhgj.proto.Mergedintoaccount;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class HeXiaoZhangChaFragment extends BaseFragment {


    private FragmentHeXiaoZhangChaBinding mBinding;
    private HeXiaoZhangChaViewModel mViewModel;
    private MineRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(HeXiaoZhangChaViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(MineRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_he_xiao_zhang_cha, container, false);
        mBinding = FragmentHeXiaoZhangChaBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mViewModel.layoutManager.set(new LinearLayoutManager(mActivity));
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        String visType = getArguments().getString("type");

        if (visType.equals("1")) {
            mViewModel.vis1.set(true);
        } else {
            mViewModel.vis2.set(true);
        }


        mSharedViewModel.hexiaoType.observe(this, s -> {
            mViewModel.vis1.set(true);
            mViewModel.vis2.set(false);

        });


        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });

        mSharedViewModel.isCheck.observe(this, fls -> {
            if (fls) {
                Mergedintoaccount.final_query.Builder builders = Mergedintoaccount.final_query.newBuilder();
                builders.setStart(mViewModel.timeOne.get()).setEnd(mViewModel.timeTwo.get());
                NetworkManager.INSTANCE.post(Apis.final_query, builders.build().toByteArray(), new OnRequestCallBack() {
                    @Override
                    public void onOk(byte[] response) throws InvalidProtocolBufferException {
                        hideProgress();
                        Mergedintoaccount.final_query final_query = Mergedintoaccount.final_query.parseFrom(response);
                        Log.e("final_query", final_query.toString());
                        List<Mergedintoaccount.order> orders = final_query.getOrderListList();
                        mViewModel.data.clear();
                        for (Mergedintoaccount.order item : orders) {
                            HeXiaoBean bean = new HeXiaoBean();
                            bean.setAmount(item.getAmount());
                            bean.setFlag(item.getFlag());
                            bean.setOrder_no(item.getOrderNo());
                            bean.setPay_type(item.getPayType());
                            bean.setPay_type_desc(item.getPayTypeDesc());
                            bean.setStatus(item.getStatus());
                            bean.setTime(item.getTime());
                            bean.setSelect(false);
                            mViewModel.data.add(bean);
                        }
                        mViewModel.adapter.notifyChange();
                        mViewModel.zhong.set(final_query.getTotalAmount());
                        mViewModel.shao_yu.set(final_query.getAmountScan());
                        mViewModel.shua_yu.set(final_query.getAmountPos());
                        mViewModel.res.set(R.mipmap.icon_unselect);
                        mViewModel.gong.set("一共0笔，总交易金额为：0.00元");
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        hideProgress();
                        showShortToast(errorMessage);
                    }
                });
            }
        });


        Mergedintoaccount.final_query.Builder builders = Mergedintoaccount.final_query.newBuilder();
        builders.setStart(mViewModel.timeOne.get()).setEnd(mViewModel.timeTwo.get());
        NetworkManager.INSTANCE.post(Apis.final_query, builders.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                hideProgress();
                Mergedintoaccount.final_query final_query = Mergedintoaccount.final_query.parseFrom(response);
                Log.e("final_query", final_query.toString());
                List<Mergedintoaccount.order> orders = final_query.getOrderListList();
                for (Mergedintoaccount.order item : orders) {
                    HeXiaoBean bean = new HeXiaoBean();
                    bean.setAmount(item.getAmount());
                    bean.setFlag(item.getFlag());
                    bean.setOrder_no(item.getOrderNo());
                    bean.setPay_type(item.getPayType());
                    bean.setPay_type_desc(item.getPayTypeDesc());
                    bean.setStatus(item.getStatus());
                    bean.setTime(item.getTime());
                    bean.setSelect(false);
                    mViewModel.data.add(bean);
                }
                mViewModel.adapter.get().getLoadMoreModule().loadMoreEnd();
                mViewModel.zhong.set(final_query.getTotalAmount());
                mViewModel.shao_yu.set(final_query.getAmountScan());
                mViewModel.shua_yu.set(final_query.getAmountPos());
                mViewModel.gong.set("一共0笔，总交易金额为：0.00元");
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
                showShortToast(errorMessage);
            }
        });


    }

    @Override
    public void loadInitData() {
        super.loadInitData();
    }

    public class ClickProxy {
        public void back() {
            nav().navigateUp();
        }

        public void history() {
            nav().navigate(R.id.action_heXiaoZhangChaFragment_to_heHistoryFragment);

        }

        public void check() {
            showProgress();
            Mergedintoaccount.final_query.Builder builders = Mergedintoaccount.final_query.newBuilder();
            builders.setStart(mViewModel.timeOne.get()).setEnd(mViewModel.timeTwo.get());
            NetworkManager.INSTANCE.post(Apis.final_query, builders.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) throws InvalidProtocolBufferException {
                    hideProgress();
                    Mergedintoaccount.final_query final_query = Mergedintoaccount.final_query.parseFrom(response);
                    Log.e("final_query", final_query.toString());
                    List<Mergedintoaccount.order> orders = final_query.getOrderListList();
                    mViewModel.data.clear();
                    for (Mergedintoaccount.order item : orders) {
                        HeXiaoBean bean = new HeXiaoBean();
                        bean.setAmount(item.getAmount());
                        bean.setFlag(item.getFlag());
                        bean.setOrder_no(item.getOrderNo());
                        bean.setPay_type(item.getPayType());
                        bean.setPay_type_desc(item.getPayTypeDesc());
                        bean.setStatus(item.getStatus());
                        bean.setTime(item.getTime());
                        bean.setSelect(false);
                        mViewModel.data.add(bean);
                    }
                    mViewModel.adapter.notifyChange();
                    mViewModel.zhong.set(final_query.getTotalAmount());
                    mViewModel.shao_yu.set(final_query.getAmountScan());
                    mViewModel.shua_yu.set(final_query.getAmountPos());
                    mViewModel.res.set(R.mipmap.icon_unselect);
                    mViewModel.gong.set("一共0笔，总交易金额为：0.00元");
                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                    hideProgress();
                    showShortToast(errorMessage);
                }
            });

        }

        public void timeOne() {
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(mActivity, mViewModel.lisOne,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            dialog.show();
        }

        public void timeTwo() {
            Calendar calendar = Calendar.getInstance();
            DatePickerDialog dialog = new DatePickerDialog(mActivity, mViewModel.lisTwo,
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH));
            dialog.show();
        }

        public void sumbit() {
            StringBuilder order = new StringBuilder();
            for (HeXiaoBean item : mViewModel.data) {
                if (item.isSelect()) order.append(item.getOrder_no() + ",");
            }
            int bishu = 0;
            float total = 0;
            ArrayList<HeXiaoBean> data = mViewModel.data;
            for (HeXiaoBean item : data) {
                if (item.isSelect()) {
                    bishu++;
                    total = total + Float.parseFloat(item.getAmount());
                }
            }

            if (bishu == 0) {
                showLongToast("请先选择交易");
                return;
            }

            mViewModel.gong.set("一共" + bishu + "笔，总交易金额为：" + total + "元");
            Bundle bundle = new Bundle();
            bundle.putString("money", total + "");
            bundle.putString("bishu", bishu + "");
            bundle.putString("order", order.toString());
            nav().navigate(R.id.action_heXiaoZhangChaFragment_to_heXiaoChaNextFragment, bundle);
        }


        public void change() {
            nav().navigate(R.id.action_heXiaoZhangChaFragment_to_jieShuanMoFragment);
        }

        public void gong() {
            int bishu = 0;
            float total = 0;
            ArrayList<HeXiaoBean> data = mViewModel.data;
            bishu = data.size();
            for (HeXiaoBean item :
                    data) {
                item.setSelect(true);
                total = total + Float.parseFloat(item.getAmount());
            }
            mViewModel.gong.set("一共" + bishu + "笔，总交易金额为：" + total + "元");
            mViewModel.adapter.notifyChange();
            mViewModel.res.set(R.mipmap.icon_select);
        }

        public void itemOnClick(int position) {
            HeXiaoBean bean = mViewModel.data.get(position);
            bean.setSelect(!bean.isSelect());
            int bishu = 0;
            float total = 0;
            ArrayList<HeXiaoBean> data = mViewModel.data;
            for (HeXiaoBean item : data) {
                if (item.isSelect()) {
                    bishu++;
                    total = total + Float.parseFloat(item.getAmount());
                }
            }
            mViewModel.gong.set("一共" + bishu + "笔，总交易金额为：" + total + "元");
            if (bishu == data.size()) {
                mViewModel.res.set(R.mipmap.icon_select);
            } else {
                mViewModel.res.set(R.mipmap.icon_unselect);
            }
            mViewModel.adapter.notifyChange();
        }

        public void loadMoreListener() {

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {

    }
}
